package org.jianfa.rpc.consumer;

import org.jianfa.learn.common.service.IUserService;
import org.jianfa.rpc.consumer.client.RpcConsumer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

public class SimpleRpcConsumerApplication {

    public static void main(String[] args) throws Exception{
        //1.初始化客户端cliet
        RpcConsumer.init();

        //2.循环给服务器写数据
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int count = 1;
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            if ("bye".equals(line)) {
                break;
            }

            if ("send".equals(line)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String date = sdf.format(new Date());

                Map<String, IUserService> userServiceMap = RpcConsumer.getProxys();
                System.out.println(String.format("第%d轮请求一共有%d个服务器。时间: %s", count, userServiceMap.size(), date));

                if (userServiceMap.size() > 0) {
                    Set<String> hosts = userServiceMap.keySet();
                    String host = RpcConsumer.findHostByFastResponseTime(hosts);
                    IUserService userService = userServiceMap.get(host);
                    System.out.println(String.format("    >>>> 客户端请求服务器 %s", host));

                    long start = System.currentTimeMillis();
                    String result = userService.sayHello("are you ok !!");
                    long end = System.currentTimeMillis();
                    long responseTime = (end - start);
                    System.out.println(String.format("    <<<< %s", result));
                    RpcConsumer.recordResponseTime(host, responseTime);
                }

                count++;
            }
        }
    }
}
